#include "beep.h"
#include "RGB.h"
#include "drivers/dev_pwm.h"
#include "rtdef.h"
#include "rtthread.h"
#include "rttypes.h"


#define PWM_DEV_NAME        "pwm4"  /* PWM设备名称 */
#define BEEP_CHANNEL        3   /* PWM通道 */

struct rt_device_pwm *pwm_dev_beep;      /* PWM设备句柄 */
static rt_timer_t beep_timer = RT_NULL;

#define LOG_TAG              "BEEP"
#define LOG_LVL              LOG_LVL_DBG
#include <ulog.h>


static void beep_thread_entry(void *parameter) ;

int beep_device_init(void)
{
    rt_err_t ret = RT_EOK;

    /* 查找设备 */
    pwm_dev_beep = (struct rt_device_pwm *)rt_device_find(PWM_DEV_NAME);
    if (pwm_dev_beep == RT_NULL)
    {
        LOG_E("pwm sample run failed! can't find %s device!\n", PWM_DEV_NAME);
        ret = -RT_ERROR;
    }
    
    rt_pwm_enable(pwm_dev_beep, BEEP_CHANNEL);
    
    beep_timer =rt_timer_create("beep_timer",beep_ctrl_times,RT_NULL,2,RT_TIMER_FLAG_PERIODIC|RT_TIMER_FLAG_SOFT_TIMER);
    if (beep_timer!=RT_NULL)
    {
        rt_timer_start(beep_timer);
    }
    return ret;
}

INIT_APP_EXPORT(beep_device_init); //rtt 自动初始化PWM设备


static uint8_t beep_times;

int32_t beep_set_times(uint8_t times)
{
    beep_times = times;
    return 0;
}

void beep_set_tune(rt_uint32_t tune, rt_uint32_t ctrl)
{
    rt_pwm_set(pwm_dev_beep, BEEP_CHANNEL, tune, ctrl);
}

/**
  * @brief  called by cycle, control beep times.(one BEEP_PERIOD)
  * @param  NULL
  * @retval
  */
void beep_ctrl_times()
{
    static uint8_t show_num=0,stop_num=0;
    static uint8_t ticks;

    /* The beep works after the system starts 3s */
    if (rt_tick_get() / 1000 >3)
    {
        if (show_num ==0 && stop_num ==0)
        {
            show_num = beep_times;
            stop_num =100;
        }
        else if (show_num ==0)
        {
            stop_num--;
            beep_set_tune(1000000,0);
        }
        else
        {
            ticks++;
            if (ticks<50)
            {
                beep_set_tune(1000000,0);
                aRGB_led_show(LED_Black);
            }else if (ticks<100)
            {
                beep_set_tune(1000000,500000);
                aRGB_led_show(LED_Red);
            }
            else
            {
                ticks=0;
                show_num--;
            }
        }
    }
}
